<template>
    <div class="singer">
      <list-view :data="singers" @select="selectSinger"></list-view>
        <router-view></router-view>
    </div>
</template>

<script>
  const HOT_NAME = '热门';
  const HOT_SINGER_LEN = 10;
  import {getSingerList} from "api/singer";
  import {ERR_OK} from "api/config";
  import Singer from "common/js/singer"
  import ListView from "base/listView/listView"
  import {mapMutations} from 'vuex'
  export default {
        name: "singer",
      data() {
          return {
            singers: []
          }
      },
      created() {
          this._getSingerList()
      },
      methods: {
          selectSinger(singer) {
            this.$router.push({
              path: `/singer/${singer.id}`
            });
            this.setSinger(singer)
          },
          _getSingerList() {
            getSingerList().then((res) => {
              if (res.code === ERR_OK) {
                this.singers = this._normalizeSinger(res.data.list)
              }
            })
          },
          _normalizeSinger(list) {
            // 遍历数据 分类热门 聚合A-Z
          let map = {
            hot: {
              title: HOT_NAME,
              items: []
            }
          }
          list.forEach((item,index) => {
              // 前十条数据作为热门
            if (index < HOT_SINGER_LEN) {
              map.hot.items.push(new Singer({
                name: item.Fsinger_name,
                id: item.Fsinger_mid
              }))
            }
            // 根据index做聚类
            const key = item.Findex;
            if(!map[key]) {
              // 如果map里无key 赋值
              map[key] = {
                title: key,
                items: []
              }
            }
            map[key].items.push(new Singer({
              name: item.Fsinger_name,
              id: item.Fsinger_mid
            }))
          })
          // 处理有序列表 得到map
          let hot = []
          let ret = []
          for (let key in map) {
            let val = map[key];
            // 检测是字母A-Z
            if (val.title.match(/[a-zA-Z]/)) {
              ret.push(val)
            } else if (val.title === HOT_NAME) {
              // 检测到是热门
              hot.push(val)
            }
          }
          // 做降序排布
          ret.sort((a, b) => {
            // a-b为降序
            // b-a为升序
            return  a.title.charCodeAt(0)-b.title.charCodeAt(0)
          })
          // 整合为一维数组
          return hot.concat(ret)
        },
          // vuex 方法映射
          ...mapMutations({
            setSinger: 'SET_SINGER'
          })
      },
      components: {
        ListView
      }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .singer
    position: fixed // 固定父元素高度
    top: 88px
    bottom: 0
    width: 100%
</style>
